package com.hyperf.core.validation.constraintvalidators;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyperf.core.validation.constraints.Json;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * JSON字符串验证的实现类
 *
 * @author lizhaoyang
 */
public class JsonValidator  implements ConstraintValidator<Json, String> {

    private boolean required;

    @Override
    public void initialize(Json constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (!required && StrUtil.isEmpty(s)) {
            return true;
        } else {
            try {
                JSONObject.parseObject(s);
                return true;
            } catch (Exception exception) {
                return false;
            }
        }
    }
}
